﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Validation;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using DevExpress.Web;
using TheHeGeo.Util;
using TheHeGeoDao;

namespace TheHeGeo.UserControl
{
    public partial class UcSensorManagerEnglish : System.Web.UI.UserControl
    {
        private int RowIndex = -1;
        protected void Page_Init(object sender, EventArgs e)
        {
            LoadGrvData();

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session[SessionConst.SES_GRV_SENSOR_MANAGEMENT] = null;
                LoadGrvData();
            }
            else
            {
                grvData.DataSource = Session[SessionConst.SES_GRV_SENSOR_MANAGEMENT];
            }
            
        }

        protected void LoadGrvData()
        {
            LoadThietBiColumnItems();
            var cu = ((SessionUser)Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
            var data = (from d in DaoHelper.Entities.PhanQuyenDuAns
                        join t in DaoHelper.Entities.ThietBis on d.MaDuAn equals t.MaDuAn
                join s in DaoHelper.Entities.Sensors on t.MaThietBi equals s.MaThietBi
                where (d.UserName.Equals(cu)&&t.Status==0)
                select s).ToList();
            var dt = new DataTable();
            dt.Columns.Add("MaSensor", typeof(string));
            dt.Columns.Add("TenSensor", typeof(string));
            dt.Columns.Add("MoTa", typeof(string));
            dt.Columns.Add("MappingNo", typeof(string));
            dt.Columns.Add("MaThietBi", typeof (string));
            dt.Columns.Add("Latitude", typeof (string));
            dt.Columns.Add("Longitude", typeof(string));
            dt.Columns.Add("Altitude", typeof(string));
            dt.Columns.Add("Mk", typeof (string));
            dt.Columns.Add("DonVi", typeof (string));
            dt.Columns.Add("DonViTg", typeof (string));
            dt.Columns.Add("ThoiGianLayMauCanhBao", typeof (int));
            dt.Columns.Add("MaxValue", typeof(double));
            dt.Columns.Add("MinValue", typeof(double));
            dt.Columns.Add("SoLanQuaGioiHan", typeof(int));
            foreach (var sensor in data)
            {
                var dr = dt.NewRow();
                dr["MaSensor"] = sensor.MaSensor;
                dr["TenSensor"] = sensor.TenSensor;
                dr["MoTa"] = sensor.MoTa;
                dr["MappingNo"] = sensor.MappingNo;
                dr["MaThietBi"] = sensor.MaThietBi;
                dr["Latitude"] = sensor.Latitude;
                dr["Longitude"] = sensor.Longitude;
                dr["Altitude"] = sensor.Altitude;
                dr["DonVi"] = sensor.DonVi;
                dr["DonViTg"] = "1";
                dr["ThoiGianLayMauCanhBao"] = sensor.ThoiGianLayMauCanhBao.HasValue?sensor.ThoiGianLayMauCanhBao:0;
                dr["MaxValue"] = sensor.MaxValue.HasValue ? sensor.MaxValue : 0;
                dr["MinValue"] = sensor.MinValue.HasValue ? sensor.MinValue : 0;
                dr["SoLanQuaGioiHan"] = sensor.SoLanQuaGioiHan.HasValue ? sensor.SoLanQuaGioiHan : 0;
                dt.Rows.Add(dr);
            }
            Session[SessionConst.SES_GRV_SENSOR_MANAGEMENT] = dt;
            grvData.DataSource = dt;
            grvData.DataBind();
        }

        protected void LoadThietBiColumnItems()
        {
            var cbb = grvData.Columns["MaThietBi"] as GridViewDataComboBoxColumn;
            if (cbb == null) return;
            string user = ((SessionUser)(Session[SessionConst.SES_USER])).NguoiSuDung.UserName;
            cbb.PropertiesComboBox.Items.Clear();
            cbb.PropertiesComboBox.ValueType = typeof(string);
            var dt = (from d in DaoHelper.Entities.PhanQuyenDuAns
                      join e in DaoHelper.Entities.ThietBis on d.MaDuAn equals e.MaDuAn
                      join a in DaoHelper.Entities.DuAns on d.MaDuAn equals a.MaDuAn
                      where (d.UserName.Equals(user) && e.Status != Common.EquipmentMoved)
                      select new
                      {
                          e.MaThietBi,
                          e.TenThietBi,
                          a.MaDuAn,
                          a.TenDuAn
                      }).ToList();
            foreach (var tb in dt)
            {
                var temp = cbb.PropertiesComboBox.Items;
                string txt = tb.TenThietBi + "- Dự án:" + tb.TenDuAn;
                if (temp.FindByText(txt) == null)
                    temp.Add(txt, tb.MaThietBi);
            }
        }

        protected void Msg()
        {
            ScriptManager.RegisterStartupScript(Page, GetType(), "alert1", "<script type='text/javascript'>alert('You do not have permission to edit information')</script>", false);
        }

        protected bool CanEdit(string maThietBi)
        {
            string user = ((SessionUser)(Session[SessionConst.SES_USER])).NguoiSuDung.UserName;
            var tb = (from p in DaoHelper.Entities.PhanQuyenDuAns
                      join q in DaoHelper.Entities.ThietBis on p.MaDuAn equals q.MaDuAn
                      where (p.UserName.Equals(user) && q.MaThietBi.Equals(maThietBi) && p.Role.Equals(Common.R_W_D))
                      select q).ToList();
            if (tb.Count > 0)
                return true;
            return false;
        }

        protected void grvData_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
        {
            if (CanEdit((string) e.Values["MaThietBi"]))
            {
                try
                {
                    var a = DaoHelper.Entities.Sensors.AsEnumerable()
                        .FirstOrDefault(p => p.MaSensor.Equals(e.Values["MaSensor"].ToString()));
                    if (a != null)
                    {
                        DaoHelper.Entities.Sensors.Remove(a);
                        DaoHelper.Entities.SaveChanges();
                    }
                }
                catch (Exception)
                {
                    throw new Exception("Delete unsuccessfull, please try again.");
                }
            }
            else
            {
                throw new ArgumentException("You do not have permission to edit information");
            }
            e.Cancel = true;
            grvData.CancelEdit();
            LoadGrvData();
        }
        protected bool ValidateThietBi(string maTB)
        {
            var tB = (from p in DaoHelper.Entities.ThietBis
                      where (p.MaThietBi == maTB && p.Status != Common.EquipmentMoved)
                      select p).FirstOrDefault();
            if (tB.Status == Common.EquipmentRunning)
                return true;
            return false;

        }
        protected void grvData_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            grvData.Columns["Mk"].Visible = false;
            if (CanEdit((string) e.NewValues["MaThietBi"]))
            {
                if (!ValidateThietBi(e.NewValues["MaThietBi"].ToString()))
                    throw new ArgumentException("The equipment is stopping using, please choose another equipment!");
                try
                {
                    grvData.DoRowValidation();
                    string mass = e.NewValues["MaSensor"].ToString();
                    var temp = e.NewValues["MappingNo"].ToString();
                    string matb = e.NewValues["MaThietBi"].ToString();
                    if (!UserHelper.CheckFollowPwdEncrypt((string) e.NewValues["Mk"], mass))
                    {
                        throw new ArgumentException("Sensor Id or password incorrect");
                    }
                    int map;
                    if (!int.TryParse(temp.Substring(temp.Length - 1, 1), out map))
                    {
                        map = -1;
                    }

                    CheckMappingNo(matb,mass, map);

                    var a = DaoHelper.Entities.Sensors.AsEnumerable()
                        .FirstOrDefault(p => p.MaSensor.Equals(mass));
                    if (a != null)
                        throw new ArgumentException("Sensor ID is existing");

                    var t = DaoHelper.Entities.ThietBis.AsEnumerable().FirstOrDefault(p => p.MaThietBi.Equals(matb));
                    if (t == null)
                        throw new ArgumentException("Equipment not available");

                    var iso = new Sensor();
                    iso.MaSensor = e.NewValues["MaSensor"].ToString();
                    iso.TenSensor = e.NewValues["TenSensor"] == null
                        ? string.Empty
                        : e.NewValues["TenSensor"].ToString();
                    iso.MoTa = e.NewValues["MoTa"] == null ? string.Empty : e.NewValues["MoTa"].ToString();
                    iso.MaThietBi = matb;
                    iso.MappingNo = map;
                    iso.MaxValue = Convert.ToDouble(e.NewValues["MaxValue"].ToString());
                    iso.MinValue = Convert.ToDouble(e.NewValues["MinValue"].ToString());
                    iso.SoLanQuaGioiHan = Convert.ToInt32(e.NewValues["SoLanQuaGioiHan"].ToString()); 
                    var longt = (string)(e.NewValues["Longitude"]);
                    var lat = (string) (e.NewValues["Latitude"]);
                    var us = ((SessionUser)Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
                    if (string.IsNullOrEmpty(longt) && string.IsNullOrEmpty(lat))
                    {

                        var pDa = (from s in DaoHelper.Entities.Sensors
                                    join tb in DaoHelper.Entities.ThietBis on s.MaThietBi equals tb.MaThietBi
                                    join q in DaoHelper.Entities.PhanQuyenDuAns on tb.MaDuAn equals q.MaDuAn
                                    join da in DaoHelper.Entities.DuAns on q.MaDuAn equals da.MaDuAn

                                    where ( tb.MaThietBi == iso.MaThietBi&& tb.Status==0 &&q.UserName==us)
                                    select da).FirstOrDefault();
                        if (pDa != null)
                        {
                            iso.Longitude = pDa.Longitude;
                            iso.Latitude = pDa.Latitude;
                        }
                        else
                        {
                            iso.Longitude = "";
                            iso.Latitude = "";  
                        }
                    }
                    else
                    {
                        iso.Longitude = longt;
                        iso.Latitude = lat;
                    }
                        
                    iso.Altitude = (string) (e.NewValues["Altitude"]);
                    iso.CongThuc = "1*x";
                    DaoHelper.Entities.Sensors.Add(iso);
                    DaoHelper.Entities.SaveChanges();

                }
                catch (ArgumentException)
                {
                    throw;
                }
                
                catch (Exception)
                {
                    throw new Exception("Add unsuccessfull, please try again.");
                }
            }
            else
            {
                throw new ArgumentException("You do not have permission to edit information");
            }
            e.Cancel = true;
            grvData.CancelEdit();
            LoadGrvData();
        }

        protected void CheckMappingNo(string matb,string mass, int map)
        {
            if (map != -1)
            {
                var b = DaoHelper.Entities.Sensors.AsEnumerable()
                    .FirstOrDefault(p => p.MappingNo == map &&!p.MaSensor.Equals(mass)&&p.MaThietBi.Equals(matb));
                if (b != null)
                {
                    throw new ArgumentException("Position " + (map + 1) + " is used by sensor: " +
                                        b.TenSensor);
                }
            }
        }

        protected void DeleteSensorData(string maSensor)
        {
            try
            {

                var vSensorTest = (from v in DaoHelper.Entities.SensorValuesTests
                    where (v.MaSensor == maSensor)
                    select v).ToList();
                DaoHelper.Entities.SensorValuesTests.RemoveRange(vSensorTest);

                var vSensor1000 = (from v in DaoHelper.Entities.SensorValues1000
                    where (v.MaSensor == maSensor)
                    select v).ToList();
                DaoHelper.Entities.SensorValues1000.RemoveRange(vSensor1000);

                var vSensorLatest = (from v in DaoHelper.Entities.SensorLatestValues
                    where (v.MaSensor == maSensor)
                    select v).ToList();
                DaoHelper.Entities.SensorLatestValues.RemoveRange(vSensorLatest);
                //DaoHelper.Entities.SaveChanges();
                //return 1;

            }
            catch (Exception ex)
            {
                
            }
        }

        protected void grvData_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            if (CanEdit((string) e.OldValues["MaThietBi"]))
            {
                if (!ValidateThietBi(e.NewValues["MaThietBi"].ToString()))
                    throw new ArgumentException("The equipment is stopping using, please choose another equipment!");
                try
                {
                    grvData.DoRowValidation();
                    var mass = e.OldValues["MaSensor"].ToString();
                    var map = Convert.ToInt32(e.NewValues["MappingNo"].ToString());

                    CheckMappingNo(e.NewValues["MaThietBi"].ToString(),mass, map);

                    var a = DaoHelper.Entities.Sensors.AsEnumerable()
                        .First(p => p.MaSensor.Equals(mass));
                    if (a != null)
                    {
                        if (e.OldValues["MaThietBi"] != e.NewValues["MaThietBi"])
                            DeleteSensorData(a.MaSensor);
                        a.TenSensor = e.NewValues["TenSensor"] == null
                            ? string.Empty
                            : e.NewValues["TenSensor"].ToString();
                        a.MoTa = e.NewValues["MoTa"] == null ? string.Empty : e.NewValues["MoTa"].ToString();
                        a.MappingNo = map;
                        a.Longitude = (string)(e.NewValues["Longitude"]);
                        a.Latitude = (string)(e.NewValues["Latitude"]);
                        a.Altitude = (string)(e.NewValues["Altitude"]);
                        a.MaxValue = Convert.ToDouble(e.NewValues["MaxValue"].ToString());
                        a.MinValue = Convert.ToDouble(e.NewValues["MinValue"].ToString());
                        a.SoLanQuaGioiHan = Convert.ToInt32(e.NewValues["SoLanQuaGioiHan"].ToString()); 
                        DaoHelper.Entities.SaveChanges();
                    }
                }
                catch (ArgumentException)
                {
                    throw;
                }
                catch (Exception)
                {
                    throw new Exception("Update unsuccessfull, please try again.");
                }
            }
            else
            {
                throw new ArgumentException("You do not have permission to edit information");
            }
            e.Cancel = true;
            grvData.CancelEdit();
            LoadGrvData();
        }

        protected void grvData_InitNewRow(object sender, DevExpress.Web.Data.ASPxDataInitNewRowEventArgs e)
        {
            var c = grvData.Columns["MaSensor"] as GridViewDataColumn;
            if (c != null)
            {
                c.ReadOnly = false;
            }

            var d=grvData.Columns["MaThietBi"] as GridViewDataColumn;
            if (d != null)
            {
                d.ReadOnly = false;
            }

            var h = grvData.Columns["Mk"] as GridViewDataColumn;
            if (h != null)
            {
                h.Visible = true;
            }

            e.NewValues["MappingNo"] = "Incorrect";
        }

        protected void grvData_StartRowEditing(object sender, DevExpress.Web.Data.ASPxStartRowEditingEventArgs e)
        {
            var c = grvData.Columns["MaSensor"] as GridViewDataColumn;
            if (c != null)
            {
                c.ReadOnly = true;
            }
        }

        protected void grvData_ParseValue(object sender, DevExpress.Web.Data.ASPxParseValueEventArgs e)
        {
            if (e.FieldName.Equals("TenSensor"))
            {
                if (e.Value == null || string.IsNullOrEmpty(e.Value.ToString()))
                {
                    throw new Exception("Please enter sensor name");
                }
            }

            if (e.FieldName.Equals("MaSensor"))
            {
                if (e.Value == null || string.IsNullOrEmpty(e.Value.ToString()))
                {
                    throw new Exception("Please enter sensor id");
                }
            }

            if (e.FieldName.Equals("MaThietBi"))
            {
                if (e.Value == null || string.IsNullOrEmpty(e.Value.ToString()))
                {
                    throw new Exception("Please choice equiment");
                }
            }

            if (e.FieldName.Equals("Mk") &&grvData.Columns["Mk"].Visible)
            {
                if (e.Value == null || string.IsNullOrEmpty(e.Value.ToString()))
                {
                    throw new Exception("Please enter password");
                }
            }
        }

        protected void grvData_CancelRowEditing(object sender, DevExpress.Web.Data.ASPxStartRowEditingEventArgs e)
        {
            var h = grvData.Columns["Mk"] as GridViewDataColumn;
            if (h != null)
            {
                h.Visible = false;
            }
        }

        protected void grvData_CustomJSProperties(object sender, ASPxGridViewClientJSPropertiesEventArgs e)
        {
            if (grvData.IsEditing)
            {
                e.Properties["cpEditingRowIndex"] = grvData.EditingRowVisibleIndex;
                RowIndex = grvData.EditingRowVisibleIndex;
            }
            else
            {
                e.Properties["cpEditingRowIndex"] = -1;
                RowIndex = -1;
            }
        }
        protected void grvData_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
        {
            if (e.Parameters == "EditPossition")
            {
                grvData.RowUpdating += (s, e1) => { e1.NewValues["Latitude"] = "21"; e1.NewValues["Longitude"] = "105"; };
                grvData.UpdateEdit();
            }
        }
    }
}